<?php

namespace app\common\model;

use app\common\service\StatusService;
use think\Db;
use think\Model;


class Cart extends Model
{

    

    

    // 表名
    protected $name = 'cart';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
	    'status_text'
    ];
    
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = StatusService::$cartStatusList;
		return $list[$value] ??'';
	}
    

	public function user()
	{
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function goods()
	{
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function spec()
	{
		return $this->belongsTo('goodsSpec', 'goods_spec_id', 'id', '', 'left')->setEagerlyType(0);
	}

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
	
	public function getRow($userId, $goodsId, $specId)
	{
		$row = $this->where([
			'user_id' => $userId,
			'goods_id' => $goodsId,
			'goods_spec_id' => $specId,
			'status' => StatusService::STATUS_NORMAL
		])
			->find();
		return $row;
	}
	
	public function getCartByUserId($userId)
	{
		$rows = Db::name('cart')->alias('c')
			->join('goods g', 'c.goods_id = g.id', 'left')
			->join('seller se', 'g.seller_id = se.id', 'left')
			->join('goodsSpec s', 'c.goods_spec_id = s.id', 'left')
			->where(['c.user_id' => $userId, 'c.status' => StatusService::STATUS_NORMAL, 'g.status' => StatusService::STATUS_NORMAL])
			->field('c.id, c.number, c.goods_id, c.goods_spec_id, g.goods_name, g.image, g.price, g.stock_number, s.name as spec_name, s.stock_number as spec_number, s.image as spec_image, s.price as spec_price,  g.seller_id, se.name as seller_name')
			->order(['c.update_time' => 'desc'])
			->select();
		return $rows;
	}
	
	protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
